package org.ihelpuoo.weboo.module;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.ihelpuoo.lang.ExceptionUtils;
import org.ihelpuoo.lang.SegmentNotFoundException;
import org.ihelpuoo.parser.segment.Segment;

public class WebooPageServlet extends WebooServlet
{
	private static final long	serialVersionUID	= 5175660951944613339L;

	private Logger				log					= Logger.getLogger(WebooPageServlet.class);

	@Override
	protected void doHTTP(HttpServletRequest request, HttpServletResponse response)
	{
		super.doHTTP(request,response);
		String path = request.getServletPath();
		int pos = path.lastIndexOf('.');
		path = path.substring(1,pos);
		pos = path.indexOf('/');
		try
		{
			Module m;
			Segment seg;

			if (pos == -1)
			{
				m = moduleManager.getDefaultModule();
				seg = m.getModuleContext().patterns(request).create(path);
			}
			else
			{
				try
				{
					m = moduleManager.getModule(path.substring(0,pos));
				}
				catch (Exception e)
				{
					if (log.isDebugEnabled())
						log.debug("can not find module for \"" + request.getServletPath()
								+ "\", user default module!");
					m = moduleManager.getDefaultModule();
				}
				seg = m.getModuleContext().patterns(request).create(path);
			}
			m.processHTML(seg,moduleManager.getControllers(m.getName()),request,response);
		}
		catch (SegmentNotFoundException e)
		{
			response.setStatus(404);
			log.warn(ExceptionUtils.dumpBrief(e));
		}
		catch (Exception e)
		{
			response.setStatus(500);
			log.error(ExceptionUtils.dump(e));
		}
	}

}
